package cgl.narada.transport.up2p;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;

import org.apache.log4j.Logger;

import cgl.narada.protocol.Protocol;
import cgl.narada.transport.up2p.messages.Registration;

/**
 * 
 * Created on Aug 7, 2006
 * 
 * @author Harshawardhan Gadgil (hgadgil@grids.ucs.indiana.edu)
 */

public class PeerRegistrationThread extends Thread {

   static Logger log = Logger.getLogger("PeerRegistrationThread");

   private DatagramSocket socket;
   private SocketAddress relayServerSocketAddress;
   private String peerId;

   private boolean keepRunning = true;
   
   public PeerRegistrationThread(String myId, DatagramSocket sock,
            SocketAddress relayServerAddress) {
      super();
      peerId = myId;
      socket = sock;
      relayServerSocketAddress = relayServerAddress;
   }

   public void shutdown() {
      keepRunning = false;
   }
   
   public void run() {

      Registration reg = new Registration(peerId, socket
               .getLocalSocketAddress());

      DatagramPacket packet = null;
      try {
         byte[] bytes = reg.getBytes();

         byte[] data = new byte[1 + bytes.length];
         data[0] = Protocol.REGISTER_PEER;
         System.arraycopy(bytes, 0, data, 1, bytes.length);

         packet = new DatagramPacket(data, data.length,
                  relayServerSocketAddress);

      } catch (SocketException e2) {
         log.error("", e2);
      } catch (IOException e2) {
         log.error("", e2);
      }

      while (keepRunning) {
         // Send once every 20 seconds
         try {
            // log.debug("Sending REGISTRATION !");
            socket.send(packet);
         } catch (Exception e1) {
            log.error("", e1);
         }

         try {
            Thread.sleep(20000);
         } catch (InterruptedException e) {

         }
      }
   }
}
